package com.j.lemon.learn.basic.io.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author lijunjun
 * @Date 2020-02-26 12:04
 * @Description
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8089);
        System.out.println(serverSocket.getInetAddress().getHostAddress());
        while(true){
            Socket socket = serverSocket.accept();
            threadPool.execute(new Handler(socket));
        }
    }


}
class Handler implements Runnable{
    private Socket socket;

    public Handler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String s = bufferedReader.readLine();
            System.out.println("accept:"+s+",from"+socket.getInetAddress().getHostAddress());

            OutputStream outputStream = socket.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            PrintWriter printWriter = new PrintWriter(outputStreamWriter,true);
            printWriter.println("done");
            printWriter.flush();
            System.out.println("server done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
